<?php
/**
 * Created by PhpStorm.
 * User: user1
 * Date: 2018/9/3
 * Time: 14:34
 */

namespace app\common\model;


use app\common\enum\StatusEnum;
use think\Exception;

class Auth extends BaseModel
{
    protected $deleteTime = false;
    /**
     * 添加或者编辑权限
     * @param $data
     * @param $id
     * @return \think\response\Json
     */
    public static function createOrUpdateAuth($data, $id) {
        try {
            if ($data['parent_id'] > 0) {
                if (!input('param.controller', '')) {
                    throw new Exception('权限控制器不能为空');
                }
                if (!input('param.action')) {
                    throw new Exception('权限方法不能为空');
                }
            }
            $data['controller'] = input('param.controller', '');
            $data['action'] = input('param.action', '');

            if ($id > 0) {
                $auth = self::get($id);
                if (!$auth) {
                    throw new Exception('权限不存在');
                }

                $check_auth = self::where('name', '=', $data['name'])->where('id', 'neq', $id)->find();
                if ($check_auth) {
                    throw new Exception('权限名称已存在');
                }
                $auth->save($data);
            } else {
                $check_auth = self::where('name', '=', $data['name'])->find();
                if ($check_auth) {
                    throw new Exception('权限名称已存在');
                }
                $data['authStatus'] = StatusEnum::AUTH_VALID;
                self::create($data);
            }
            return return_data('保存成功！');
        } catch (Exception $e) {
            return return_data($e->getMessage(), 1);
        }
    }
}